<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="复制模板" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { copyFormSchema } from "./template.data"
  import { copyTemplate } from "./template.api"
  import { listTemplateGroup } from "../templateGroup/templateGroup.api"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  const sourceGroupId = ref("")
  const oldTemplateName = ref("")
  const emit = defineEmits(["register", "success"])
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    // labelWidth: 150,
    schemas: copyFormSchema,
    showActionButtonGroup: false,
  })
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields()
    setModalProps({ confirmLoading: false })
    oldTemplateName.value = data.name
    sourceGroupId.value = data.groupId
    const option = await listTemplateGroup({})
    await updateSchema({
      field: "groupId",
      componentProps: {
        options: unref(option),
      },
    })
    //表单赋值
    await setFieldsValue({
      ...data,
    })
  })

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate()
      if (values.name === oldTemplateName.value && values.groupId === sourceGroupId.value) {
        createMessage.error("同组下名称不能重复")
        return
      }

      setModalProps({ confirmLoading: true })
      //提交表单
      await copyTemplate({ ...values, sourceGroupId: sourceGroupId.value, targetGroupId: values.groupId })
      //关闭弹窗
      closeModal()
      //刷新列表
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
